from fastapi import HTTPException
import asyncio
import httpx
import time
import io


async def tts(chat_info):
    audio_url = 'http://127.0.0.1:9880/tts'
    gpt_weights_url = 'http://127.0.0.1:9880/set_gpt_weights'
    sovits_weights_url = 'http://127.0.0.1:9880/set_sovits_weights'

    gpt_weights_path = {"weights_path": "E:\\PycharmProject\\GPT-SoVITS\\GPT_weights\\三月七\\三月七-e10.ckpt"}
    # gpt_weights_path = {"weights_path": "E:\\PycharmProject\\GPT-SoVITS\\GPT_weights\\流萤\\流萤-e10.ckpt"}
    sovits_weights_path = {"weights_path": "E:\\PycharmProject\\GPT-SoVITS\\SoVITS_weights\\三月七\\三月七_e15_s4875.pth"}
    # sovits_weights_path = {"weights_path": "E:\\PycharmProject\\GPT-SoVITS\\SoVITS_weights\\流萤\\流萤_e15_s375.pth"}

    send_audio_info = {
        "text": str(chat_info),  # str.(required) 要合成的文本内容
        "text_lang": "zh",  # str.(required) 要合成的文本语言
        "ref_audio_path": "E:\\PycharmProject\\GPT-SoVITS\\reference audio\\三月七\\开心-别看小谛听只是叫了几声，它发言的信息量可是非常大的哟。.wav",
        # "ref_audio_path": "E:\\PycharmProject\\GPT-SoVITS\\reference audio\\流萤\\说话-因为你身上别着星穹列车的徽章呀，我在大银幕上见过！.wav",
        # str.(required) 参考音频路径
        "prompt_text": "别看小谛听只是叫了几声，它发言的信息量可是非常大的哟。",  # str.(optional) 参考音频文本
        # "prompt_text": "因为你身上别着星穹列车的徽章呀，我在大银幕上见过！",  # str.(optional) 参考音频文本
        "prompt_lang": "zh",  # str.(required) 参考音频的语言
        "top_k": 5,  # int.(optional) top k sampling
        "top_p": 1,  # float.(optional) top p sampling
        "temperature": 1,  # float.(optional) 采样温度
        "text_split_method": "cut5",  # str.(optional) 文本分割方法
        "batch_size": 1,  # int.(optional) 推理时的批处理大小
        "batch_threshold": 0.75,  # float.(optional) 批处理阈值
        "split_bucket": True,  # bool.(optional) 是否将批处理拆分为多个存储桶
        "speed_factor": 1.0,  # float.(optional) 控制合成音频的速度
        "fragment_interval": 0.3,  # float.(optional) 以控制音频片段的间隔
        "seed": -1,  # int.(optional) 随机种子的可重复性
        "media_type": "wav",  # str.(optional) 输出音频的媒体类型，支持“wav”，“raw”，“ogg”，“aac”
        "streaming_mode": False,  # bool.(optional) 是否返回流响应
    }
    save_path = f"static/audio/{int(time.time())}.wav"

    # 创建异步HTTP客户端
    async with httpx.AsyncClient() as client:
        try:
            # 发送get请求，设置声音模型
            response_gpt_weights = await client.get(gpt_weights_url, params=gpt_weights_path)
            # 异步等待0.1秒
            await asyncio.sleep(0.1)
            response_sovits_weights = await client.get(sovits_weights_url, params=sovits_weights_path)
            # 异步等待1秒
            await asyncio.sleep(0.1)
            gpt_json = response_gpt_weights.json()
            sovits_json = response_sovits_weights.json()

            if gpt_json.get("code") != 200 or sovits_json.get("success") is False:
                print(gpt_json, sovits_json)
                raise HTTPException(status_code=500, detail={
                    "code": 500,
                    "msg": ""
                           "网络异常，请重试"
                })

            # 发送POST请求
            response_tts = await client.post(audio_url, json=send_audio_info)
            # 读取音频数据
            audio_data = response_tts.read()

            # 将音频数据保存到本地文件
            with io.BytesIO(audio_data) as f:
                with open(save_path, "wb") as f2:
                    f2.write(f.read())
            # print(f"语音请求成功，文件已经保存到：{save_path}")
        except Exception as e:
            raise HTTPException(status_code=500, detail={
                "code": 500,
                "info": str(e),
                "msg": "网络异常，请重试"
            })
    return save_path
